package com.aisafer.action;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.aisafer.base.enums.ResponseEnum;
import com.aisafer.base.pojo.Response;
import com.aisafer.oss.domain.Attachment;
import com.aisafer.oss.dto.AttachmentContent;
import com.aisafer.oss.dto.AttachmentHandleReq;
import com.aisafer.oss.dto.AttachmentReq;
import com.aisafer.oss.dto.AttachmentResp;
import com.aisafer.oss.dto.AttachmentUploadReq;
import com.aisafer.oss.dto.DownReq;
import com.aisafer.oss.dto.DownResp;
import com.aisafer.oss.mapper.ModuleMapper;
import com.aisafer.oss.service.OSSService;
import com.aisafer.oss.service.impl.AttachmentHandleSercie;
import com.aisafer.oss.utils.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("/attach")
public class AttachmentAction {

	private static final Logger logger = LoggerFactory.getLogger(AttachmentAction.class);

	@Autowired
	private OSSService OSSService;

	@Autowired
	AttachmentHandleSercie attachmentHandleSercie;
	
	@Autowired
	ModuleMapper moduleMapper;

	@RequestMapping("/list")
	public String list(Map<String, Object> model) {
		return "attach/list";
	}

	@RequestMapping("/add")
	public String add(Map<String, Object> model) {
		model.put("moduleList", moduleMapper.findAll(null));
		return "attach/add";
	}

	@RequestMapping("/getList")
	@ResponseBody
	public String getList(AttachmentHandleReq req) {
		logger.info(JSONUtil.toJson(req));
		List<Attachment> list = attachmentHandleSercie.getAttachmentList(req);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", "0");
		jsonObject.put("msg", "200");
		jsonObject.put("count", "10");
		jsonObject.put("data", list);

		return jsonObject.toJSONString();
	}

	@RequestMapping(value = "/upload", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String uploadfile(HttpServletRequest request, HttpServletResponse response, AttachmentUploadReq req) {
		return saveFileMultipart(request, response, req);
	}

	@RequestMapping(value = "/download", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void download(HttpServletRequest request, HttpServletResponse response, DownReq down) {
		try {
			DownResp resp = OSSService.download(down);
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\"" +String.valueOf(System.currentTimeMillis()) + resp.getFileType() + "\"");
			response.addHeader("Content-Length", "" + resp.getContent().length);
			response.setContentType("application/octet-stream;charset=UTF-8");
			OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
			outputStream.write(resp.getContent());
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	private String saveFileMultipart(HttpServletRequest request, HttpServletResponse response,
			AttachmentUploadReq uploadParm) {
		ObjectMapper om = new ObjectMapper();
		try {
			MultipartHttpServletRequest mulReq = (MultipartHttpServletRequest) request;
			MultipartFile file = mulReq.getFile("file");
			AttachmentReq req = new AttachmentReq();
			AttachmentContent attachmentContent = new AttachmentContent();
			req.setModuleKey(uploadParm.getModuleKey());
			req.setUrlExpire(uploadParm.getUrlExpire());
			attachmentContent = new AttachmentContent();
			attachmentContent.setContent(file.getBytes());
			attachmentContent.setFileSize(Integer.valueOf(attachmentContent.getContent().length).longValue());
			attachmentContent.setFileType(uploadParm.getFileType());
			attachmentContent.setFileName(uploadParm.getFileName());
			attachmentContent.setCategoryType(uploadParm.getCategoryType());
			attachmentContent.setSourceSystem(uploadParm.getSourceSystem());
			req.setAttachmentContent(attachmentContent);
			Response<AttachmentResp> result = OSSService.uploadFile(req);
			// RequestUtils.out(response, JSONUtil.toJson(result));
			return om.writeValueAsString(result);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			Response<String> res = new Response<String>();
			res.setCode(ResponseEnum.FAILURE5010.getCode());
			res.setMsg(ResponseEnum.FAILURE5010.getMessage());
			try {
				logger.error(om.writeValueAsString(res));
				return om.writeValueAsString(res);
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

}
